<link rel="stylesheet" href="../public/jqGrid/css/ui.jqgrid.css"/>
<link rel="stylesheet" href="../public/jquery-ui/themes/base/jquery-ui.css"/>
<link rel="stylesheet" href="../css/cust.jqGrid.css"/>

<section class="content-header">
    <h1>
        组织机构
        <small>组织机构管理</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboad"></i> 装备管理系统</a></li>
        <li><a href="#">系统设置</a></li>
        <li class="active">组织机构</li>
    </ol>
</section>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-body">
                    <table id="grid-table"></table>
                    <div id="grid-pager"></div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="../public/jqGrid/js/jquery.jqGrid.min.js"></script>
<script src="../public/jqGrid/js/minified/i18n/grid.locale-cn.js"></script>
<script type="text/javascript">

    var DepartmentTable = function () {
        return {

            bind_listener: function () {
                $('i.visible_check').on('click', function () {
                    //TODO ajax post alter data
                    swal('Send an ajax request toggle checked/unchecked state.');
                    $(this).toggleClass('fa-check-square-o fa-square-o');
                });

                $('select.roles_select').select2({
                    placeholder: "请点击选择选取角色...",
                }).on('select2:selecting', function (evt) {
                    //TODO listening about select role
                    swal('Selecting Role By Id [' + evt.params.args.data.id + ']');
                }).on('select2:unselecting', function (evt) {
                    //TODO listening about remove role
                    swal('Unselecting Role By Id [' + evt.params.args.data.id + ']');
                });

                $.bootstrapLoading.end();

            },

            getDepartLevel: function (callback_func) {
                $.ajax({
                    url: '/System/Const/DepartLevel',
                    type: 'get',
                    dataType: 'json',
                    success: function (data) {
                        if (data) {
                            role_list = menu_mgr.recursion_role(data.roles);
                            callback_func();
                        } else {
                            swal('异常！', '没有获取到角色信息！', 'error');
                        }
                    },
                    error: function (req, err_code, err_msg) {
                        swal('异常！', err_msg, 'error');
                    }
                });
            },

            recursion_menu: function (data, level, parent) {
                var level = (level == undefined) ? 0 : level;
                var parent = (parent == undefined) ? "" : parent;

                for (var i = 0; i < data.length; i++) {
                    var o_data = data[i];
                    var t_data = {id: o_data.id, url: o_data.url, visible: o_data.visible, memo: o_data.memo};
                    t_data.name = '<i class="' + o_data.ico + '"></i>&nbsp;' + o_data.name;
                    t_data.visible = (o_data.visible == 1) ? '<i class="visible_check handle fa fa-check-square-o"></i>' : '<i class="visible_check handle fa fa-square-o"></i>';
                    t_data.roles = '<select multiple="multiple" class="roles_select" style="width: 100%;">';
                    var o_data_roles = {};
                    if (o_data.roles != undefined) {
                        for (var j = 0; j < o_data.roles.length; j++) {
                            o_data_roles[o_data.roles[j].role_id] = o_data.roles[j].role_name;
                        }
                    }
                    for (var x = 0; x < role_list.length; x++) {
                        if (role_list[x].id == undefined) {
                            t_data.roles += '<optgroup label="' + role_list[x].text + '">';
                            for (var y = 0; y < role_list[x].children.length; y++) {
                                var selected = "";
                                var sloption = role_list[x].children[y];
                                if (o_data_roles[sloption.id] != undefined) {
                                    selected = "selected";
                                }
                                t_data.roles += '<option value="' + sloption.id + '"' + selected + '>' + sloption.text + '</option>';
                            }
                            t_data.roles += '</optgroup>';
                        } else {
                            var selected = "";
                            if (o_data_roles[role_list[x].id] != undefined) {
                                selected = "selected";
                            }
                            t_data.roles += '<option value="' + role_list[x].id + '"' + selected + '>' + role_list[x].text + '</option>';
                        }
                    }
                    t_data.roles += '</select>';
                    t_data.level = level;
                    t_data.parent = parent;
                    t_data.loaded = true;
                    t_data.expanded = (o_data.children != undefined);
                    t_data.isLeaf = (o_data.children == undefined);

                    menu_data.push(t_data);

                    if (o_data.children != undefined) {
                        menu_mgr.recursion_menu(o_data.children, level + 1, o_data.id);
                    }
                }
            },

            generatejqGrid: function (departData) {
                DepartmentTable.getDepartLevel(function () {
                    DepartmentTable.recursion_menu(departData);


                });
            },

            init: function () {
                if (jQuery().jqGrid) {
                    $.ajax({
                        url: '/Setting/Depart',
                        type: 'get',
                        dataType: 'json',
                        success: function (data) {
                            $.bootstrapLoading.start();
                            DepartmentTable.generatejqGrid(data);
                        },
                        error: function (req, err_code, err_msg) {
                            swal('异常！', err_msg, 'error');
                        }
                    });
                }
            }
        }
    }();

    DepartmentTable.init();

    jQuery(function ($) {
        var grid_selector = "#grid-table";
        var pager_selector = "#grid-pager";

        jQuery(grid_selector).jqGrid({
            //direction: "rtl",

            data: grid_data,
            datatype: "local",
            height: 'auto',
            colNames: ["编号", "单位名称", "类别", "级别", "可视", "主管", "单位人员"],
            colModel: [
                {
                    name: 'myac', index: '', width: 80, fixed: true, sortable: false, resize: false,
                    formatter: 'actions',
                    formatoptions: {
                        keys: true,

                        delOptions: {recreateForm: true, beforeShowForm: beforeDeleteCallback},
                        //editformbutton:true, editOptions:{recreateForm: true, beforeShowForm:beforeEditCallback}
                    }
                },
                {name: 'id', index: 'id', width: 60, sorttype: "int", editable: true},
                {
                    name: 'sdate',
                    index: 'sdate',
                    width: 90,
                    editable: true,
                    sorttype: "date",
                    unformat: pickDate
                },
                {
                    name: 'name',
                    index: 'name',
                    width: 150,
                    editable: true,
                    editoptions: {size: "20", maxlength: "30"}
                },
                {
                    name: 'stock',
                    index: 'stock',
                    width: 70,
                    editable: true,
                    edittype: "checkbox",
                    editoptions: {value: "Yes:No"},
                    unformat: aceSwitch
                },
                {
                    name: 'ship',
                    index: 'ship',
                    width: 90,
                    editable: true,
                    edittype: "select",
                    editoptions: {value: "FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}
                },
                {
                    name: 'note',
                    index: 'note',
                    width: 150,
                    sortable: false,
                    editable: true,
                    edittype: "textarea",
                    editoptions: {rows: "2", cols: "10"}
                }
            ],

            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: pager_selector,
            altRows: true,
            //toppager: true,

            multiselect: true,
            //multikey: "ctrlKey",
            multiboxonly: true,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    styleCheckbox(table);
                    updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },

            editurl: "/dummy.html",//nothing is saved
//            caption: "菜单列表",
            autowidth: true

        });

        //enable search/filter toolbar
        //jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})

        //switch element when editing inline
        function aceSwitch(cellvalue, options, cell) {
            setTimeout(function () {
                $(cell).find('input[type=checkbox]')
                    .wrap('<label class="inline" />')
                    .addClass('ace ace-switch ace-switch-5')
                    .after('<span class="lbl"></span>');
            }, 0);
        }

        //enable datepicker
        function pickDate(cellvalue, options, cell) {
            setTimeout(function () {
                $(cell).find('input[type=text]')
                    .datepicker({format: 'yyyy-mm-dd', autoclose: true});
            }, 0);
        }


        //navButtons
        jQuery(grid_selector).jqGrid('navGrid', pager_selector,
            { 	//navbar options
                edit: true,
                editicon: 'fa fa-pencil blue',
                add: true,
                addicon: 'fa fa-plus-circle purple',
                del: true,
                delicon: 'fa fa-trash red',
                search: true,
                searchicon: 'fa fa-search orange',
                refresh: true,
                refreshicon: 'fa fa-refresh green',
                view: true,
                viewicon: 'fa fa-search-plus grey',
            },
            {
                //edit record form
                //closeAfterEdit: true,
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_edit_form(form);
                }
            },
            {
                //new record form
                closeAfterAdd: true,
                recreateForm: true,
                viewPagerButtons: false,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_edit_form(form);
                }
            },
            {
                //delete record form
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    if (form.data('styled')) return false;

                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_delete_form(form);

                    form.data('styled', true);
                },
                onClick: function (e) {
                    alert(1);
                }
            },
            {
                //search form
                recreateForm: true,
                afterShowSearch: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    style_search_form(form);
                },
                afterRedraw: function () {
                    style_search_filters($(this));
                }
                ,
                multipleSearch: true,
                /**
                 multipleGroup:true,
                 showQuery: true
                 */
            },
            {
                //view record form
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                }
            }
        )


        function style_edit_form(form) {
            //enable datepicker on "sdate" field and switches for "stock" field
            form.find('input[name=sdate]').datepicker({format: 'yyyy-mm-dd', autoclose: true})
                .end().find('input[name=stock]')
                .addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');

            //update buttons classes
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-primary').prepend('<i class="icon-ok"></i>');
            buttons.eq(1).prepend('<i class="icon-remove"></i>')

            buttons = form.next().find('.navButton a');
            buttons.find('.ui-icon').remove();
            buttons.eq(0).append('<i class="icon-chevron-left"></i>');
            buttons.eq(1).append('<i class="icon-chevron-right"></i>');
        }

        function style_delete_form(form) {
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-danger').prepend('<i class="icon-trash"></i>');
            buttons.eq(1).prepend('<i class="icon-remove"></i>')
        }

        function style_search_filters(form) {
            form.find('.delete-rule').val('X');
            form.find('.add-rule').addClass('btn btn-xs btn-primary');
            form.find('.add-group').addClass('btn btn-xs btn-success');
            form.find('.delete-group').addClass('btn btn-xs btn-danger');
        }

        function style_search_form(form) {
            var dialog = form.closest('.ui-jqdialog');
            var buttons = dialog.find('.EditTable')
            buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet');
            buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt');
            buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search');
        }

        function beforeDeleteCallback(e) {
            var form = $(e[0]);
            if (form.data('styled')) return false;

            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_delete_form(form);

            form.data('styled', true);
        }

        function beforeEditCallback(e) {
            var form = $(e[0]);
            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_edit_form(form);
        }


        //it causes some flicker when reloading or navigating grid
        //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
        //or go back to default browser checkbox styles for the grid
        function styleCheckbox(table) {
            /**
             $(table).find('input:checkbox').addClass('ace')
             .wrap('<label />')
             .after('<span class="lbl align-top" />')


             $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
             .find('input.cbox[type=checkbox]').addClass('ace')
             .wrap('<label />').after('<span class="lbl align-top" />');
             */
        }


        //unlike navButtons icons, action icons in rows seem to be hard-coded
        //you can change them like this in here if you want
        function updateActionIcons(table) {
            /**
             var replacement =
             {
                 'ui-icon-pencil' : 'icon-pencil blue',
                 'ui-icon-trash' : 'icon-trash red',
                 'ui-icon-disk' : 'icon-ok green',
                 'ui-icon-cancel' : 'icon-remove red'
             };
             $(table).find('.ui-pg-div span.ui-icon').each(function(){
						var icon = $(this);
						var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
						if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
					})
             */
        }

        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
                {
                    'ui-icon-seek-first': 'fa fa-angle-double-left bigger-140',
                    'ui-icon-seek-prev': 'fa fa-angle-left bigger-140',
                    'ui-icon-seek-next': 'fa fa-angle-right bigger-140',
                    'ui-icon-seek-end': 'fa fa-angle-double-right bigger-140'
                };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        }

        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({container: 'body'});
            $(table).find('.ui-pg-div').tooltip({container: 'body'});
        }

        //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');


    });
</script>